//
//  XLSampleDataFilter.m
//  AudioWaveDemo
//
//  Created by ilongge on 2023/4/17.
//

#import "XLSampleDataFilter.h"
#import <UIKit/UIKit.h>
@interface XLSampleDataFilter()

@end

@implementation XLSampleDataFilter


- (NSArray *)filteredSamplesForSampleData:(NSData *)sampleData binSize:(NSInteger)binSize maxHeight:(CGFloat)height
{
    NSMutableArray *filteredSamples = [NSMutableArray array];
    NSUInteger  sampleCount = sampleData.length / sizeof(SInt16);
    SInt16 *bytes = (SInt16 *)sampleData.bytes;
    SInt16 maxSample = 0;
    for (NSUInteger i= 0; i < sampleCount; i += binSize) {
        SInt16 sampleBin[binSize];
        for (NSUInteger j = 0; j < binSize; j++) {
            sampleBin[j] = CFSwapInt16LittleToHost(bytes[i + j]);
        }
        SInt16 value = [self maxValueInArray:sampleBin ofSize:binSize];
        [filteredSamples addObject:@(value)];
        if (value > maxSample) {
            maxSample = value;
        }
    }
    CGFloat scaleFactor = (height/2)/maxSample;
    for (NSUInteger i = 0; i < filteredSamples.count; i++) {
        filteredSamples[i] = @([filteredSamples[i] integerValue] * scaleFactor);
    }
    return filteredSamples;
}

- (NSArray *)filteredSamplesForSampleData:(NSData *)sampleData size:(CGSize)size
{
    NSMutableArray *filteredSamples = [NSMutableArray array];
    NSUInteger  sampleCount = sampleData.length / sizeof(SInt16);
    NSUInteger  binSize = sampleCount / size.width;
    SInt16 *bytes = (SInt16 *)sampleData.bytes;
    SInt16 maxSample = 0;
    for (NSUInteger i= 0; i < sampleCount; i += binSize) {
        SInt16 sampleBin[binSize];
        for (NSUInteger j = 0; j < binSize; j++) {
            sampleBin[j] = CFSwapInt16LittleToHost(bytes[i + j]);
        }
        SInt16 value = [self maxValueInArray:sampleBin ofSize:binSize];
        [filteredSamples addObject:@(value)];
        if (value > maxSample) {
            maxSample = value;
        }
    }
    CGFloat scaleFactor = (size.height/2)/maxSample;
    for (NSUInteger i = 0; i < filteredSamples.count; i++) {
        filteredSamples[i] = @([filteredSamples[i] integerValue] * scaleFactor);
    }
    return filteredSamples;
}


- (SInt16)maxValueInArray:(SInt16[])values ofSize:(NSUInteger)size {
    SInt16 maxValue = 0;
    for (int i = 0; i < size; i++) {
        if (abs(values[i] > maxValue)) {
            maxValue = abs(values[i]);
        }
    }
    return maxValue;
}
@end
